/*
 * Copyright 2009 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.devtools.simple.compiler.expressions;

import com.google.devtools.simple.classfiles.Field;
import com.google.devtools.simple.classfiles.Method;
import com.google.devtools.simple.compiler.Compiler;
import com.google.devtools.simple.compiler.symbols.FunctionSymbol;
import com.google.devtools.simple.compiler.types.BooleanType;

/**
 * This class represents constant expressions of boolean values.
 * 
 * @author Herbert Czymontek
 */
public final class ConstantBooleanExpression extends ConstantExpression {
  // Constant boolean value
  private final boolean boolConst;

  /**
   * Creates a new instance of ConstantBooleanExpression
   * 
   * @param position  source code start position of expression
   * @param boolConst  constant boolean value
   */
  public ConstantBooleanExpression(long position, boolean boolConst) {
    super(position);

    this.boolConst = boolConst;
  }

  /**
   * Returns value of this constant.
   * 
   * @return  constant value
   */
  public boolean getBoolean() {
    return boolConst;
  }

  @Override
  public Expression resolve(Compiler compiler, FunctionSymbol currentFunction) {
    type = BooleanType.booleanType;
    return this;
  }

  @Override
  public void generate(Method m) {
    m.generateInstrLdc(boolConst ? 1 : 0);
  }

  @Override
  public void generate(Field f) {
    f.setConstantIntegerValue(boolConst ? 1 : 0);
  }

  @Override
  public void generateBranchOnFalse(Method m, Method.Label falseLabel) {
    if (!boolConst) {
      m.generateInstrGoto(falseLabel);
    }
  }

  @Override
  public void generateBranchOnTrue(Method m, Method.Label trueLabel) {
    if (boolConst) {
      m.generateInstrGoto(trueLabel);
    }
  }

  @Override
  public String toString() {
    return boolConst ? "True" : "False";  // COV_NF_LINE
  }
}
